<template>
  <div class="example-full">
    <el-page-header @back="$router.go(-1)" content="文件上传"> </el-page-header>
    <!-- 表头 上传文件 -->
    <div class="box">
      <div tabindex="0" class="el-upload el-upload--text" style="height: 30px">
        <file-upload
          class="el-upload__input"
          :multiple="true"
          :drop="true"
          :add-index="addIndex"
          v-model="files"
          :thread="3"
          :timeout="600 * 1000"
          :directory="directory"
          :postAction="postAction"
          :custom-action="submitUpload"
          @input-filter="inputFilter"
          @input-file="inputFile"
          ref="upload"
        >
          <div
            :class="{
              'el-upload-dragger': true,
              'is-dragover': $refs.upload && $refs.upload.dropActive,
            }"
            style="height: 100px"
          >
            <i class="el-icon-upload" style="margin-top: 5px"></i>
            <div class="el-upload__text">将文件拖到此处</div>
          </div>
        </file-upload>
      </div>
      <div
        style="
          position: fixed;
          left: 650px;
          display: inline-block;
          margin-top: 20px;
        "
      >
        <div style="margin-bottom: 8px">上传文件</div>
        <label class="el-button el-button--default" :for="name">
          <span :for="name">选择文件</span>
        </label>
      </div>
      <div
        style="
          position: fixed;
          left: 850px;
          display: inline-block;
          margin-top: 20px;
        "
      >
        <div style="margin-bottom: 8px">上传文件夹</div>
        <label class="el-button el-button--default" @click="onAddFolder">
          <span>选择文件夹</span>
        </label>
      </div>
    </div>

    <!-- 上传详细情况 -->
    <p>
      <span> 列表个数：{{ files.length }} </span>
      <span> 成功：{{ successFileNum }} </span>
      <span> 失败：{{ failFileNum }} </span>
    </p>

    <!-- 表格 展示数据-->
    <div class="table_container box">
      <el-table
        :data="files"
        highlight-current-row
        stripe
        size="medium"
        style="width: 100%"
        empty-text="暂无文件上传"
      >
        <el-table-column
          property="response.fac"
          align="center"
          label="电厂"
          width="80"
        ></el-table-column>
        <el-table-column
          property="response.fileNum"
          align="center"
          label="文件编码"
          width="100"
        ></el-table-column>
        <el-table-column
          :formatter="spvFormatter"
          align="center"
          label="spv相关"
          width="80"
        ></el-table-column>
        <el-table-column
          :formatter="fileName"
          align="center"
          label="文件名"
          width="100"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          :formatter="fileSize"
          align="center"
          label="文件大小"
          width="80"
        >
          <template slot-scope="scope">
            {{ (scope.row.size / 1024 / 1024).toFixed(2) }} MB
          </template>
        </el-table-column>
        <el-table-column align="center" label="上传进度" width="100">
          <template slot-scope="scope">
            <el-progress
              :text-inside="true"
              :stroke-width="20"
              :percentage="Number(scope.row.progress)"
            ></el-progress>
          </template>
        </el-table-column>

        <el-table-column align="center" label="当前状态" width="80">
          <template slot-scope="scope">
            <span v-if="scope.row.response.success == true">解析成功</span>
            <span
              v-else-if="
                scope.row.response.success == false && scope.row.success
              "
            >
              解析失败
            </span>
            <span v-else-if="scope.row.progress == '100.00'">解析中...</span>
            <span v-else-if="scope.row.success">解析中...</span>
            <span
              v-else-if="
                $refs.upload.active === true && scope.row.progress == '0.00'
              "
            >
              准备上传
            </span>
            <span v-else-if="scope.row.active">上传中...</span>
            <span v-else>未上传</span>
          </template>
        </el-table-column>

        <el-table-column
          :formatter="codeNum"
          align="center"
          label="提取编码数"
          width="80"
        ></el-table-column>
        <el-table-column
          property="response.RightNum"
          align="center"
          label="现有编码数"
          width="80"
        ></el-table-column>
        <el-table-column
          property="response.FaultNum"
          align="center"
          label="失效编码数"
          width="80"
        ></el-table-column>
        <el-table-column
          :formatter="faultRate"
          align="center"
          label="失效占比"
          width="100"
        ></el-table-column>
        <el-table-column
          property="response.FacAF"
          align="center"
          label="全部冻结(工厂级)"
          width="80"
        ></el-table-column>
        <el-table-column
          property="response.FacFB"
          align="center"
          label="冻结采购(工厂级)"
          width="80"
        ></el-table-column>
        <el-table-column
          property="response.GpAF"
          align="center"
          label="全部冻结(集团级)"
          width="80"
        ></el-table-column>
        <el-table-column
          property="response.GpFB"
          align="center"
          label="冻结采购(集团级)"
          width="80"
        ></el-table-column>

        <el-table-column align="center" label="操作" width="240">
          <template slot-scope="scope">
            <el-button
              @click.prevent="
                scope.row.active
                  ? $refs.upload.update(scope.row, { error: 'cancel' })
                  : false
              "
              type="warning"
              size="mini"
              v-if="scope.row.active"
            >
              取消
            </el-button>
            <el-button
              @click.prevent="
                $refs.upload.update(scope.row, {
                  active: true,
                  error: '',
                  progress: '0.00',
                  success: false,
                })
              "
              type="primary"
              size="mini"
              v-else
              v-show="scope.row.response.success != true"
            >
              上传
            </el-button>

            <el-button size="mini" v-show="scope.row.response.wordPath">
              <a :href="scope.row.response.wordPath" target="_blank"> 下载 </a>
            </el-button>
            <el-button
              @click.prevent="$refs.upload.remove(scope.row)"
              type="danger"
              size="mini"
            >
              移除
            </el-button>
            <el-button
              @click="openInfoTable(scope.row.response.fileName)"
              type="success"
              size="mini"
              v-show="scope.row.response.success"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 底部按钮组 -->
    <div class="footer">
      <el-button
        type="primary"
        round
        :disabled="files.length == 0"
        @click.prevent="$refs.upload.active = true"
        v-if="failFileNum === 0"
      >
        上传所有
      </el-button>
      <el-button
        type="primary"
        round
        :disabled="files.length == 0"
        @click.prevent="reloadFailFile()"
        v-else
      >
        重新上传
      </el-button>
      <el-button
        type="warning"
        round
        :disabled="files.length == 0"
        @click.prevent="$refs.upload.active = false"
      >
        取消所有
      </el-button>
      <el-button
        type="success"
        round
        :disabled="files.length == 0"
        @click.prevent="removeSuccessFile()"
      >
        移除成功文件
      </el-button>
      <el-button
        type="danger"
        round
        :disabled="files.length == 0"
        @click.prevent="$refs.upload.clear()"
      >
        移除所有
      </el-button>
    </div>

    <!-- 查看选中文件中的物资编码识别及信息表（表一） -->
    <el-dialog
      title="物资编码识别及信息表"
      :visible.sync="dialog1Visible"
      width="90%"
    >
      <el-table id="table1" :data="tableData1" style="width: 100%">
        <el-table-column
          property="fac"
          label="电厂"
          width="100"
        ></el-table-column>
        <el-table-column
          property="file_num"
          label="文件编码"
          width="200"
        ></el-table-column>
        <el-table-column
          property="spv"
          label="spv相关"
          width="100"
        ></el-table-column>
        <el-table-column
          property="file_name"
          label="文件名"
          width="200"
        ></el-table-column>
        <el-table-column
          property="file_size"
          label="文件大小"
          width="100"
        ></el-table-column>
        <el-table-column
          property="code"
          label="物资编码"
          width="100"
        ></el-table-column>
        <el-table-column
          property="state"
          label="识别状态分类"
          width="120"
        ></el-table-column>
        <el-table-column
          property="factory_state"
          label="物料状态（工厂级）"
          width="100"
        ></el-table-column>
        <el-table-column
          property="group_state"
          label="物料状态（集团级）"
          width="100"
        ></el-table-column>
        <el-table-column
          property="cpn_level"
          label="备件分级"
          width="100"
        ></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog1Visible = false"> 取 消 </el-button>
        <el-button type="success" @click="downloadTable1()"> 下 载 </el-button>
      </div>
    </el-dialog>

    <!-- 查看选中文件中的物资编码识别结果统计表（表二） -->
    <el-dialog
      title="物资编码识别结果统计表"
      :visible.sync="dialog2Visible"
      width="90%"
    >
      <el-table id="table2" :data="tableData2" style="width: 100%">
        <el-table-column
          property="fac"
          label="电厂"
          width="100"
        ></el-table-column>
        <el-table-column
          property="file_num"
          label="文件编码"
          width="100"
        ></el-table-column>
        <el-table-column
          property="spv"
          label="spv相关"
          width="80"
        ></el-table-column>
        <el-table-column
          property="file_name"
          label="文件名"
          width="200"
        ></el-table-column>
        <el-table-column
          property="file_size"
          label="文件大小"
          width="100"
        ></el-table-column>
        <el-table-column
          :formatter="codeNum"
          label="提取编码数"
          width="100"
        ></el-table-column>
        <el-table-column
          property="right_num"
          label="现有编码数"
          width="100"
        ></el-table-column>
        <el-table-column
          property="fault_num"
          label="失效编码数"
          width="100"
        ></el-table-column>
        <el-table-column
          property="fault_per"
          label="失效占比"
          width="100"
        ></el-table-column>
        <!-- <el-table-column
          property="rec_num"
          label="推荐编码数"
          width="100"
        ></el-table-column> -->
        <el-table-column
          property="facAF_num"
          label="全部冻结（工厂级）"
          width="100"
        ></el-table-column>
        <el-table-column
          property="facFB_num"
          label="冻结采购（工厂级）"
          width="100"
        ></el-table-column>
        <el-table-column
          property="gpAF_num"
          label="全部冻结（集团级）"
          width="100"
        ></el-table-column>
        <el-table-column
          property="gpFB_num"
          label="冻结采购（集团级）"
          width="100"
        ></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog2Visible = false">取 消</el-button>
        <el-button type="success" @click="downloadTable2()"> 下 载 </el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import FileUpload from "vue-upload-component";
import { baseUrl } from "../config/config";
import {
  getResAnalysis,
  getOneFileAnalysis,
  getOneFileResult,
  createTable1,
  createTable2,
  getHighlightUrl,
} from "../api/getData";
export default {
  components: {
    FileUpload,
  },

  data() {
    return {
      files: [], //文件列表
      addIndex: false,
      name: "file",
      directory: false, // 是否支持上传文件夹
      postAction: "/analysis/analysis",
      headers: {
        "Content-Type": "multipart/form-data",
      },
      uploadAuto: false, // 是否自动上传
      postAction: baseUrl + "/analysis/analysis",
      tableData1: [],
      tableData2: [],
      selection: [], // 选中的文件名数组
      dialog1Visible: false,
      dialog2Visible: false,
    };
  },
  computed: {
    // 计算上传成功数
    successFileNum() {
      let num = 0;
      this.files.map((item) => {
        if (item.response.success) {
          num++;
        }
      });
      return num;
    },
    // 失败数
    failFileNum() {
      let num = 0;
      this.files.map((item) => {
        //
        if (item.error != "") {
          num++;
        } else if (item.success && !item.response.success) {
          num++;
        }
      });
      return num;
    },
  },
  methods: {
    // 文件过滤器
    inputFilter(newFile, oldFile, prevent) {
      // if (newFile && (!oldFile || newFile.file !== oldFile.file)) {
      //   // Create a blob field
      //   // 创建 blob 字段
      //   newFile.blob = "";
      //   let URL = window.URL || window.webkitURL;
      //   if (URL && URL.createObjectURL) {
      //     newFile.blob = URL.createObjectURL(newFile.file);
      //   }
      //   // Thumbnails
      //   // 缩略图
      //   newFile.thumb = "";
      //   if (newFile.blob && newFile.type.substr(0, 6) === "image/") {
      //     newFile.thumb = newFile.blob;
      //   }
      // }
    },
    // 添加、更新、移除文件触发事件
    inputFile(newFile, oldFile) {
      //更新
      if (newFile && oldFile) {
        // update
        console.log("update");

        if (newFile.active && !oldFile.active) {
          // beforeSend
          console.log("beforeSend");
        }
        if (newFile.progress !== oldFile.progress) {
          // progress
          console.log("progress");
        }
        if (newFile.error && !oldFile.error) {
          // error
          console.log("error");
        }
        if (newFile.success && !oldFile.success) {
          // success
          console.log("success");
          if (this.successFileNum === this.files.length) {
            this.openResultTable();
          }
        }
      }
      //删除
      if (!newFile && oldFile) {
        // remove
        if (oldFile.success && oldFile.response.id) {
          // $.ajax({
          //   type: 'DELETE',
          //   url: '/upload/delete?id=' + oldFile.response.id,
          // })
        }
      }

      //自动上传
      if (
        Boolean(newFile) !== Boolean(oldFile) ||
        oldFile.error !== newFile.error
      ) {
        if (this.uploadAuto && !this.$refs.upload.active) {
          this.$refs.upload.active = true;
        }
      }
    },
    // 自定义文件上传操作
    async submitUpload(file, component) {
      let formData = new FormData();
      formData.append("test", file.file, file.file.filename || file.name);
      formData.append("type", 0);
      let xhr = new XMLHttpRequest();
      xhr.open("POST", file.postAction);
      return await component.uploadXhr(xhr, file, formData);
    },
    // 上传文件夹
    onAddFolder() {
      if (!this.$refs.upload.features.directory) {
        alert("Your browser does not support");
        return;
      }
      let input = this.$refs.upload.$el.querySelector("input");
      input.directory = true;
      input.webkitdirectory = true;
      this.directory = true;
      input.onclick = null;
      input.click();
      input.onclick = (e) => {
        this.directory = false;
        input.directory = false;
        input.webkitdirectory = false;
      };
    },
    // 打开物资编码识别及信息表
    async openInfoTable(filename) {
      // 拼接文件名数组
      let fileNameList = [];
      // 查看单个文件
      if (filename) {
        fileNameList = [filename];
      } else {
        fileNameList = this.files.map((item) => {
          return item.response.fileName;
        });
      }
      this.selection = fileNameList;
      // 判断是否选中文件
      if (fileNameList.length) {
        try {
          // 获取表一的数据
          const data = await getOneFileResult(fileNameList);

          if (data.success) {
            // 数组合并
            let list = [];
            for (let i = 0; i < data.list.length; i++) {
              list = list.concat(data.list[i]);
              console.log(list);
            }
            console.log("表一", list);
            this.tableData1 = list;
            // 显示表一对话框
            this.dialog1Visible = true;
          } else {
            throw new Error("获取数据失败");
          }
        } catch (err) {
          console.log("获取数据失败", err);
        }
      } else {
        this.$message.error("请选择文件");
      }
    },
    // 下载物资编码识别及信息表
    async downloadTable1() {
      // 判断是否选中文件
      if (this.selection.length) {
        try {
          // 获取表一的数据
          const data = await createTable1(this.selection);

          if (data.success) {
            window.open(data.url);
          } else {
            throw new Error("下载表格1失败");
          }
        } catch (err) {
          console.log("下载表格1失败", err);
        }
      } else {
        this.$message.error("请选择文件");
      }
    },
    // 打开物资编码识别结果表
    async openResultTable() {
      // 拼接文件名数组
      let fileNameList = this.files.map((item) => {
        return item.response.fileName;
      });
      // 判断是否选中文件
      if (fileNameList && fileNameList.length) {
        try {
          // 获取表2的数据
          const data = await getOneFileAnalysis(fileNameList);

          if (data.success) {
            // console.log("表二", list);
            let list = data.list;
            // 计算疑似比率并插入
            list = list.map((item) => {
              let totalNum = item.fault_num + item.right_num;
              let FaultRate =
                ((item.fault_num / totalNum) * 100).toFixed(2) + "%";
              item.fault_per = totalNum ? FaultRate : 0;
              return item;
            });
            this.tableData2 = list;

            // 显示表二对话框
            this.dialog2Visible = true;
          } else {
            throw new Error("获取数据失败");
          }
        } catch (err) {
          console.log("获取数据失败", err);
        }
      } else {
        this.$message.error("请选择文件");
      }
    },
    // 下载物资编码识别结果表
    async downloadTable2() {
      // 拼接文件名数组
      let fileNameList = this.files.map((item) => {
        return item.response.fileName;
      });
      // 判断是否选中文件
      if (fileNameList && fileNameList.length) {
        try {
          // 获取物资编码识别结果表的数据
          const data = await createTable2(fileNameList);

          if (data.success) {
            window.open(data.url);
          } else {
            throw new Error("下载表格2失败");
          }
        } catch (err) {
          console.log("下载表格2失败", err);
        }
      } else {
        this.$message.error("请选择文件");
      }
    },
    // 重新上传失败文件
    reloadFailFile() {
      this.files.map((item) => {
        if (!item.response.success) {
          this.$refs.upload.update(item, {
            active: true,
            error: "",
            progress: "0.00",
            success: false,
          });
        }
      });
    },
    // 移除解析成功的文件
    removeSuccessFile() {
      this.files.map((item) => {
        if (item.response.success) {
          this.$refs.upload.remove(item);
        }
      });
    },
    // 文件名格式化
    fileName(row, column) {
      if (row.response.fileName) {
        return row.response.fileName;
      }
      let name = row.name;
      let leftIndex = name.lastIndexOf("/");
      let rightIndex = name.lastIndexOf(".");
      name = name.substring(leftIndex + 1, rightIndex);
      return name;
    },
    // 文件大小格式化
    fileSize(row, column) {
      let res = "";
      if (row.size < 1000000) {
        res = (row.size / 1024).toFixed(0) + "KB";
      } else {
        res = (row.size / 1024 / 1024).toFixed(2) + "MB";
      }
      return res;
    },
    // 计算提取编码数
    codeNum(row, column) {
      let totalNum = 0;
      // 判断是上传表还是结果表
      if (row.success) {
        totalNum = row.response.RightNum + row.response.FaultNum;
      } else {
        totalNum = row.right_num + row.fault_num;
      }

      if (totalNum === 0) {
        return 0;
      }
      return totalNum ? totalNum : "";
    },
    // 计算失效占比
    faultRate(row, column) {
      const res = row.response;
      let totalNum = res.FaultNum + res.RightNum;
      if (totalNum === 0) {
        return "0.00%";
      }
      if (totalNum) {
        let rate = ((res.FaultNum / totalNum) * 100).toFixed(2) + "%";
        return rate;
      } else {
        return "";
      }
    },
    // spv格式化
    spvFormatter(row, column) {
      if (row.response.success) {
        return row.response.spv == "是" ? "是" : "否";
      } else {
        return "";
      }
    },
  },
};
</script>

<style scoped>
.box {
  padding: 20px;
  margin-bottom: 20px;
  border: 1px solid #eee;
  border-radius: 4px;
  background-color: #fff;
}
.el-form-item {
  margin: 20px 20px 0 0;
}

.footer {
  position: fixed;
  right: 30px;
  bottom: 20px;
}
/* 表格单元格文本居中 */
.centerText {
  text-align: center !important;
}
</style>